# -*- coding: utf-8 -*-
from tornado import gen
from qcmodule import push
from common import timetool
from settings import mysql_app_pool


@gen.coroutine
def get_push_info_zan(info_id):
    sql = (
        "select a.*, b.client_id, c.nick_name, c.avatar from app_circle_zan a, app_clientids b, app_user_info c where a.id = {} "
        "and a.to_phone = b.phone "
        "and a.phone = c.phone"
    )
    res = yield mysql_app_pool.get_one(sql.format(info_id), cursor='dict')
    raise gen.Return(res)


@gen.coroutine
def deal_push_zan():
    start_time = timetool.get_timestamp()
    sql = "select * from app_push_task where status = 0 and type in (1, 4) order by id limit 50"
    res = yield mysql_app_pool.get_all(sql, cursor='dict')
    if res:
        sql_1 = "update app_push_task set status = 1, start_time={} where type in (1, 4) and id BETWEEN {} and {};"
        yield mysql_app_pool.update(sql_1.format(start_time, res[0]['id'], res[-1]['id']))
        for item in res:
            push_info = yield get_push_info_zan(item['info_id'])
            if not push_info:
                continue
            push_info['push_type'] = item['type']
            print push_info
            info_dict = dict(
                content=push_info,
                title=push_info['nick_name'] + u"赞了你",
                text=""
            )
            push_res = yield push.push_message_to_single(info_dict, push_info['client_id'])
            end_time = timetool.get_timestamp()
            if push_res['result'] == 'ok':
                sql_2 = "update app_push_task set status = 2, push_status='{}',end_time={} where id = {};"
                yield mysql_app_pool.update(sql_2.format(push_res['status'], end_time, item['id']))
            else:
                sql_3 = "update app_push_task set status = 3, push_status='{}',end_time={} where id = {};"
                yield mysql_app_pool.update(sql_3.format(push_res['result'], end_time, item['id']))
    else:
        print 'zan nothing to do....'

